using System.Collections.Generic;
using Kopernikus.Collections.Generic;

namespace Kopernikus.Parsing.Utility
{
    public class WorkList<T>
    {
        private readonly Set<T> m_added = new Set<T>();
        private readonly bool m_allowSubsequent;
        private readonly Queue<T> m_queue = new Queue<T>();

        public WorkList(bool allowSubsequent)
        {
            m_allowSubsequent = allowSubsequent;
        }

        public int Count
        {
            get { return m_queue.Count; }
        }

        public bool Dequeue(out T item)
        {
            if (m_queue.Count > 0)
            {
                item = m_queue.Dequeue();
                if (m_allowSubsequent)
                {
                    m_added.Remove(item);
                }
                return true;
            }
            item = default(T);
            return false;
        }

        public void Enqueue(IEnumerable<T> items)
        {
            foreach (T item in items)
            {
                Enqueue(item);
            }
        }

        public bool Enqueue(T item)
        {
            if (m_added.Contains(item))
            {
                return false;
            }
            m_added.Add(item);
            m_queue.Enqueue(item);
            return true;
        }
    }
}